package com.itdaan.portal.business.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.itdaan.portal.business.controller.ShiroDbRealm.ShiroUser;
import com.itdaan.portal.business.domain.Comment;
import com.itdaan.portal.business.domain.Web;
import com.itdaan.portal.business.domain.WebType;
import com.itdaan.portal.business.service.CommentService;
import com.itdaan.portal.business.service.CommonService;
import com.itdaan.portal.business.service.WebService;
import com.itdaan.portal.business.service.WebTypeService;
import com.itdaan.portal.business.solr.ModelUtil;
import com.itdaan.portal.business.solr.Post;
import com.itdaan.portal.business.solr.SolrClient;
import com.itdaan.portal.business.solr.SolrClient4RICH;
import com.itdaan.portal.business.solr.SolrPage;
import com.itdaan.portal.common.exception.ViewException;

/**
 * 内容业务控制类 已过时
 * @author www.itdaan.com
 */
@Controller
@RequestMapping(value = "/post")
@SessionAttributes
@Deprecated
public class PostController {

	private Logger logger = LoggerFactory.getLogger(PostController.class);
	
	@Resource(name = "commonService")
	private CommonService commonService;
	@Resource(name = "webService")
	private WebService webService;
	@Resource(name = "webTypeService")
	private WebTypeService webTypeService;
	@Resource(name = "commentService")
	private CommentService commentService;
	@Autowired
	private ShiroDbRealm shiroDbRealm;
	
	@RequestMapping(value = "/show.html", method = RequestMethod.GET)
    public
    ModelAndView show(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "id", required = true) Integer id,
            @RequestParam(value = "typeId", required = true) Integer typeId
    ) throws ViewException {
		ModelAndView modelAndView = new ModelAndView();
    	try{
    		//第一步：查找该项目的信息
    		WebType webType = new WebType();
    		webType.setId(typeId);
    		webType = webTypeService.findWebTypeOne(webType);
    		modelAndView.setViewName("portal/".concat(webType.getTypeNameEn()));   		
    		int tableNum = (id-100000000*(webType.getId()-1))/100000+1;
    		String tableName = "t_".concat(webType.getTypeNameEn()).concat("_post_").concat(tableNum+"");//获取内容表的表名
    		Map<String,Object> condition = new HashMap<String, Object>();
    		condition.put("tableName", tableName);
    		condition.put("id", id);
    		condition.put("fields", "id,url,web_id as webId,title,post_time as postTime,author,view_num as viewNum,comment_num as commentNum,vote_num as voteNum");
    		Map<String,Object> map = commonService.findOne(condition);
    		Web web = new Web();
    		web.setId(Integer.parseInt(map.get("webId").toString()));
    		web = webService.findWebOne(web);    		
    		map.put("webName", web.getWebName());
    		map.put("en", web.getWebLanguageId());
    		map.put("id", id);
    		map.put("typeId", typeId);
    		modelAndView.addObject("post", map);
    		//第二步：查找相似的项目信息
    		List<Post> relateds = SolrClient.getRelated(id+"", 15);
    		modelAndView.addObject("relateds", relateds);
    		//第三步：查找评论内容
    		Comment comment = new Comment();
    		comment.setPostId(id);
    		comment.setAudit(Comment.AUDIT_OK);
    		List<Comment> comments = commentService.findCommentByPost(comment);
    		modelAndView.addObject("comments", comments);
    		comment = null;
    		
    		//查询标题关联的数据
			String q = stringFilter(map.get("title").toString());
			q = ClientUtils.escapeQueryChars(q);
			String queryString = "title:".concat(q);
			SolrPage solrPage = new SolrPage();
			solrPage.setCurPage(1);
			solrPage.setPageSize(5);
			Post post = new Post();
			post.setQueryString(queryString);
			SolrClient.startServer();
			QueryResponse solrResponse =  SolrClient.queryForRelatives(post, solrPage);
			q = q.replace("\\", "");//去掉solr转义的斜线
			q = q.replace("-", " ");//去掉中线
			q = q.replace("&", " ");//去掉参数符号
			List<SolrDocument> list = solrResponse.getResults();
			List<Post> results = new ArrayList<Post>();
			for(SolrDocument solrDocument : list){
				Post domain = new Post();
				for(String name : domain.names){
					ModelUtil.setValue(domain, name, solrDocument.get(name));
				}
				results.add(domain);
			}
			results.remove(0);
			modelAndView.addObject("results", results);
    	}catch(Exception e){
			logger.error("后台业务逻辑出现异常", e);
    	}
    	return modelAndView;
    }
	
	//ajax的方式获取内容
	@RequestMapping(value = "/content.do", method = {RequestMethod.POST,RequestMethod.GET})
    public
    ModelAndView content(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "id", required = true) Integer id
    ) throws ViewException {
		ModelAndView modelAndView = new ModelAndView();
    	try{
    		String Referer = request.getHeader("Referer");
    		if(StringUtils.isEmpty(Referer) || Referer.indexOf(id+"") == -1){
        		modelAndView.addObject("post", null);
    		}else{
    			if(id < 100000000){
    				modelAndView.setViewName("portal/blog_content");    				
    			}else{
    				modelAndView.setViewName("portal/faq_content");
    			}
    			Map<String,Object> map = new HashMap<String,Object>();
    			SolrClient4RICH.startServer();
    			String content = SolrClient4RICH.queryOne(id);
        		if(content.startsWith("€")){//如果以这个特殊字符开头，则说明是英文的stackoverflow
        			content = content.substring(1);
        			content  = new String(Base64.decode(content.getBytes("UTF-8")),"UTF-8");
        		}
    			content = content.replace("<div", "<span").replace("</div>", "</span>").replace("\t", "").replace("\n", "");    			
    			map.put("content", content);
        		modelAndView.addObject("post", map);
    		}
    	}catch(Exception e){
			logger.error("后台业务逻辑出现异常", e);
    	}
    	return modelAndView;
    }	
	
	@RequestMapping(value = "/update.html", method = {RequestMethod.POST,RequestMethod.GET})
    public
    @ResponseBody
    Map<String,Object> update(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "id", required = true) Integer id,
            @RequestParam(value = "vote", required = false) Integer vote,
            @RequestParam(value = "view", required = false) Integer view,
            @RequestParam(value = "comment", required = false) String comment
    		) throws ViewException {
		Map<String, Object> modelAndView = new HashMap<String, Object>();
        try{
    		String referer = request.getHeader("referer");
    		if(StringUtils.isEmpty(referer) || referer.indexOf(id.toString()) == -1 ){//来路我某个帖子时才更新
    			modelAndView.put("success", "false");
    			return modelAndView;
    		}
    		int typeId = id/100000000+1;
    		WebType webType = new WebType();
    		webType.setId(typeId);
    		webType = webTypeService.findWebTypeOne(webType);
    		int tableNum = (id-100000000*(typeId-1))/100000+1;
    		String tableName = "t_".concat(webType.getTypeNameEn()).concat("_post_").concat(tableNum+"");//获取内容表的表名    		
    		if(vote != null){//更新投票
				Map<String,Object> data = new HashMap<String, Object>();
				data.put("tableName", tableName);
				data.put("vote", vote);
				data.put("id", id);
				commonService.updatePostVotes(data);
				modelAndView.put("success", "true");
    		}else if(view != null){//更新查看次数
				Map<String,Object> data = new HashMap<String, Object>();
				data.put("tableName", tableName);
				data.put("view", view);
				data.put("id", id);
				commonService.updatePostViews(data);
				modelAndView.put("success", "true");
    		}else if(comment != null){//更新评论
    			Subject currentUser = SecurityUtils.getSubject();
    			if(currentUser.hasRole("illegaluser")){
    				modelAndView.put("success", "false");
    				modelAndView.put("illegal", true);
    				return modelAndView;
    			}
    			if(currentUser.isRemembered() || currentUser.isAuthenticated()){//记住的用户
    				ShiroUser shiroUser = (ShiroUser)currentUser.getPrincipals().getPrimaryPrincipal();
    				Comment postComment = new Comment();
    				postComment.setPostId(id);
    				postComment.setComment(comment);
    				postComment.setUserId(shiroUser.getId());
    				postComment.setName(shiroUser.getName());
    				postComment.setAvatar(shiroUser.getAvatar());
    				postComment.setAudit(Comment.AUDIT_TODO);
    				commentService.insertComment(postComment);
    				//查询当前ID最大的
    				modelAndView.put("success", "true");
    				modelAndView.put("login", true);
    			}else{
    				modelAndView.put("success", "false");
    				modelAndView.put("login", false);
    			}
    		}else{
    			modelAndView.put("success", "false");
    		}
        }catch(Exception e){
			logger.error("后台业务逻辑出现异常", e);
			modelAndView.put("success", "false");
    	}
		return modelAndView;
	}
	
	private String stringFilter(String str){
		  // 清除掉所有特殊字符     
	      String regEx = "[`~$%^&*()|{}':;',//[//]<>/?~！%……&*（）——|{}【】‘；：”“’？\"]";
	      Pattern p = Pattern.compile(regEx);
	      Matcher m = p.matcher(str);
	      return m.replaceAll(" ").trim();
		}
}
